package com.teacherprofile.manage.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacherprofile.common.constant.BusinessConstants;
import com.teacherprofile.common.constant.TechnicalServicesConstants;
import com.teacherprofile.common.core.domain.entity.SysUser;
import com.teacherprofile.common.domain.TechnicalServices;
import com.teacherprofile.common.enums.CheckStatus;
import com.teacherprofile.common.exception.ServiceException;
import com.teacherprofile.common.utils.DateUtils;
import com.teacherprofile.framework.manager.AsyncManager;
import com.teacherprofile.framework.manager.factory.AsyncFactory;
import com.teacherprofile.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.teacherprofile.manage.mapper.TechnicalServicesMapper;
import com.teacherprofile.manage.service.ITechnicalServicesService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 课题项目Service业务层处理
 *
 * @author qvtu
 * @date 2025-05-16
 */
@Service
public class TechnicalServicesServiceImpl extends ServiceImpl<TechnicalServicesMapper, TechnicalServices> implements ITechnicalServicesService {
    @Autowired
    private TechnicalServicesMapper technicalServicesMapper;

    @Autowired
    ISysUserService userService;

    /**
     * 查询课题项目
     *
     * @param id 课题项目主键
     * @return 课题项目
     */
    @Override
    public TechnicalServices selectTechnicalServicesById(Long id) {
        return technicalServicesMapper.selectTechnicalServicesById(id);
    }

    /**
     * 查询课题项目列表
     *
     * @param technicalServices 课题项目
     * @return 课题项目
     */
    @Override
    public List<TechnicalServices> selectTechnicalServicesList(TechnicalServices technicalServices) {
        return technicalServicesMapper.selectTechnicalServicesList(technicalServices);
    }

    /**
     * 新增课题项目
     *
     * @param technicalServices 课题项目
     * @return 结果
     */
    @Override
    public int insertTechnicalServices(TechnicalServices technicalServices) {
        String userName = technicalServices.getUserName();
        if (ObjectUtils.isEmpty(userName)) {
            throw new RuntimeException("教职工号不能为空");
        }
        // 根据教职工号查询对应的用户
        SysUser sysUser = userService.selectUserByUserName(userName);
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RuntimeException("教职工号不存在");
        }
        // 添加用户id和部门id
        technicalServices.setUserId(sysUser.getUserId());
        technicalServices.setDeptId(sysUser.getDeptId());
        technicalServices.setCreateTime(DateUtils.getNowDate());
        return technicalServicesMapper.insertTechnicalServices(technicalServices);
    }

    /**
     * 修改课题项目
     *
     * @param technicalServices 课题项目
     * @return 结果
     */
    @Override
    public int updateTechnicalServices(TechnicalServices technicalServices) {
        technicalServices.setUpdateTime(DateUtils.getNowDate());
        return technicalServicesMapper.updateTechnicalServices(technicalServices);
    }

    /**
     * 批量删除课题项目
     *
     * @param ids 需要删除的课题项目主键
     * @return 结果
     */
    @Override
    public int deleteTechnicalServicesByIds(Long[] ids) {
        return technicalServicesMapper.deleteTechnicalServicesByIds(ids);
    }

    /**
     * 删除课题项目信息
     *
     * @param id 课题项目主键
     * @return 结果
     */
    @Override
    public int deleteTechnicalServicesById(Long id) {
        return technicalServicesMapper.deleteTechnicalServicesById(id);
    }

    /**
     * 导入课题项目数据
     *
     * @param technicalServicesList
     * @return
     */
    @Transactional
    @Override
    public String importData(List<TechnicalServices> technicalServicesList) {
        if (technicalServicesList.isEmpty()) {
            throw new ServiceException("导入的数据不能为空");
        }

        // 根据教职工号去重
        Set<String> technicalServicesSet = technicalServicesList.stream()
                .map(TechnicalServices::getUserName).collect(Collectors.toSet());

        // 根据教职工号查询对应的用户
        List<SysUser> userList = userService.selectUserByUserNames(technicalServicesSet);
        if (ObjectUtils.isEmpty(userList)) {
            throw new ServiceException("导入数据中教职工号不存在");
        }

        // 将用户转为map的值，key为教职工号
        Map<String, SysUser> userMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getUserName, item -> item));
        for (TechnicalServices technicalServices : technicalServicesList) {
            SysUser sysUser = userMap.get(technicalServices.getUserName());
            technicalServices.setUserId(sysUser.getUserId());
            technicalServices.setDeptId(sysUser.getDeptId());
        }
        return saveBatch(technicalServicesList) ? "导入成功" : "导入失败";
    }

    /**
     * 课题项目数据审核
     *
     * @param technicalServices
     * @return
     */
    @Override
    public int check(TechnicalServices technicalServices) {
        if (ObjectUtils.isNull(technicalServices)) { // 非法参数
            throw new ServiceException(BusinessConstants.BUSINESS_ERROR);
        }
        if (technicalServices.getCheckStatus().equals(CheckStatus.PASS.getCode())) {
            // 审核通过
            // TODO 发送mq消息，存储数据
            //rabbitMqHelper.send(MqConstants.Exchange.SOFTWARE_COPYWRITE_EXCHANGE,
            //                    MqConstants.Key.SOFTWARE_COPYWRITE_PASS_KEY, softwareCopyrights);

            // 通知用户，审核通过
            AsyncManager.me().execute(AsyncFactory.sendPassMsgToOne(technicalServices.getUserName(), TechnicalServicesConstants.CHECKED_PASS));
        } else {
            // 审核不通过
            // TODO 发送mq消息，存储数据
            // 通知用户，审核不通过
            AsyncManager.me().execute(AsyncFactory.sendRejectMsgToOne(technicalServices.getUserName(), TechnicalServicesConstants.CHECKED_REJECT));

        }
        // 删除此条数据
//        System.out.println("审核");
//        System.out.println(patents);
        return updateById(technicalServices) ? 1 : 0;
    }
}
